package org.uim.cricket.storage.raise;

import java.util.HashMap;

import org.uim.cricket.db.DBThread;
import org.uim.cricket.db.impl.FetchAllContinents;
import org.uim.cricket.entities.FullGround;
import org.uim.cricket.entities.match.CricketMatch;
import org.uim.cricket.entities.match.Ground;
import org.uim.cricket.entities.parser.filters.impl.DefaultGroundDetailFilter;
import org.uim.cricket.entities.parser.impl.HTMLGroundEntityParser;
import org.uim.cricket.storage.Dlogger;
import org.uim.cricket.storage.backup.BackupFetchedGround;
import org.uim.cricket.storage.gui.AddNewGround;
import org.uim.cricket.storage.queries.GroundQueryGenerator;
import org.uim.cricket.storage.raise.fetch.GroundArgumentBuilder;
import org.uim.cricket.storage.raise.fetch.OrderedFetchList;
import org.uim.cricket.storage.raise.fetch.ResourceFetchable;

public class InsertNewGround extends InsertNewEntity {
	
	private Ground ground = null;
	private CricketMatch match = null;
	
	public InsertNewGround(OrderedFetchList rfetcher, CricketMatch match, Ground ground) {
		super(rfetcher);
		
		this.ground = ground;
		this.match = match;
	}
	
	public String raise() throws Exception {
		if (ground == null) return "";
		String url = null;
		
		if (this.getResourceFetcher() != null) {
			
			GroundArgumentBuilder gbuilder = new GroundArgumentBuilder();
			StringBuilder src = null;
			
			for (int i=0; i<this.getSize(); i++) {
				
				try {
					
					url = gbuilder.buildArgument(this.ground);
					ResourceFetchable fetcher = this.getFetcher(i);
					Dlogger.debug("    fetching ground page ['" + url + "']..."); 
					src = fetcher.fetchResource(url);
					if (src != null) break;
					
				} catch (Exception ex) {
					
				}
			}
			
			if (src == null) {
				throw new Exception (" * Unable to load ground " + ground.getId() + "!");
			}
			
			Dlogger.debug("    backing-up fetched ground data to the repository with ID [" + this.ground.getId() + "]...");
			new BackupFetchedGround(src).backup(new String[] {this.ground.getId()});
			
			Dlogger.debug("    parsing ground page..."); 
			HTMLGroundEntityParser grParser = new HTMLGroundEntityParser(new DefaultGroundDetailFilter());
			FullGround fg = grParser.parseGround(src);
			fg.setId(this.ground.getId());
			

			
			FetchAllContinents allCont = new FetchAllContinents();
			allCont.fetch();
			HashMap<String, Integer> conts = allCont.getMap();
			
			AddNewGround ang = new AddNewGround(null, true, fg, conts);
			ang.setVisible(true);
			
			String theContinent = ang.getTheContinent();
			String theDisplayName = ang.getDisplayName();
			
			String query = new GroundQueryGenerator(match, fg, theDisplayName, theContinent).generateQuery();
			Dlogger.debug(query);
			
			if (query != null && query.length() > 0) {
				Dlogger.debug("       Adding new ground to the database...");
				String[] qs = query.split("\n");
				for (int j=0;j<qs.length;j++) {
					qs[j] = qs[j].trim();
					if (qs[j].trim().length() == 0) continue;
					
					DBThread dbt = new DBThread(qs[j].trim()); 
					dbt.run(); dbt.close();
					
				}
				Dlogger.debug("       success.");
			}
			
			ang.dispose();
			
		} else {
			Dlogger.warn("    unable to locate resource fetcher for grounds!");
		}


		return "";
		
	}
	
	public void setMatch(CricketMatch match) {
		this.match = match;
	}
	
	public CricketMatch getMatch() {
		return match;
	}

	public void setGround(Ground ground) {
		this.ground = ground;
	}
	
	public Ground getGround() {
		return ground;
	}
	
}
